<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品信息</title>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/vue.min.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <link rel="stylesheet" href="css/bootstrap-table.min.css">
    <script src="js/bootstrap-table.min.js"></script>
    <script src="js/bootstrap-table-zh-CN.min.js"></script>
    <script type="text/javascript" src="js/layui.min.js"></script>
    <link rel="stylesheet" href="css/layui.min.css"/>
    <link href="css/bootstrap-switch.min.css" rel="stylesheet">
    <script src="js/bootstrap-switch.min.js"></script>
</head>
<style>
    #search .input1 {
        width: 150px;
        margin-right: 15px;
    }
</style>
<body>
<div class="container-fluid" id="app">
    <!--    工具栏-->
    <div id="toolbar">
        <div id="search">
            <form class="form-inline">
                <div class="form-group">
                    <label>编号</label>
                    <input id="s_code" type="text" class="form-control input1">
                </div>
                <div class="form-group">
                    <label>名称</label>
                    <input id="s_productName" type="text" class="form-control input1">
                </div>
                <div class="form-group">
                    <label>类型</label>
                    <select id="s_type" class="form-control" style="margin-right: 15px">
                        <option hidden value="0"></option>
                        <option v-for="type in typeList" :value="type.id">{{type.typeName}}</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>品牌</label>
                    <input id="s_brand" type="text" class="form-control input1">
                </div>
                <div class="form-group">
                    <label>价格</label>
                    <input id="low_p" style="width: 80px" type="text" class="form-control"> ~
                    <input id="high_p" style="width: 80px" type="text" class="form-control">
                </div>
                <div class="btn-group">
                    <button type="button" class="btn btn-primary" @click="search" style="margin-left: 15px">
                        <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
                    </button>
                    <button type="reset" class="btn btn-default" onclick="fresh()">
                        <span class="glyphicon glyphicon-repeat" aria-hidden="true"></span>
                    </button>
                </div>
            </form>
        </div>
        <div class="btn-group">
            <button id="btn_add" type="button" class="btn btn-success btn-sm" @click="clearData" data-toggle="modal"
                    data-target="#myModal">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
            </button>
            <button id="btn_edit" type="button" class="btn btn-info btn-sm" @click="findProduct">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
            </button>
            <button id="btn_delete" type="button" class="btn btn-danger btn-sm">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
            </button>
        </div>
    </div>
    <!--    bootstrap-table-->
    <table id="table"></table>

    <!--Modal模态框 -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">新增商品</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="inputEmail3" class="col-sm-2 control-label">商品编号</label>
                            <div class="col-sm-6">
                                <input v-model="code" type="text" class="form-control" id="inputEmail3"
                                       placeholder="请输入商品编号">
                            </div>
                            <span style="color: red;display: block;padding: 5px">{{errorList.pdCode}}</span>
                        </div>
                        <div class="form-group">
                            <label for="inputPassword3" class="col-sm-2 control-label">商品名称</label>
                            <div class="col-sm-6">
                                <input v-model="productName" type="text" class="form-control" id="inputPassword3"
                                       placeholder="请输入商品名称">
                            </div>
                            <span style="color: red;display: block;padding: 5px">{{errorList.pdName}}</span>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">商品类别</label>
                            <div class="col-sm-6">
                                <select v-model="type" class="form-control">
                                    <option hidden>请选择商品类别</option>
                                    <option v-for="type in typeList" :value="type.id">{{type.typeName}}</option>
                                </select>
                            </div>
                            <span style="color: red;display: block;padding: 5px">{{errorList.tid}}</span>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">商品品牌</label>
                            <div class="col-sm-6">
                                <input v-model="brand" type="text" class="form-control" placeholder="请输入商品品牌">
                            </div>
                            <span style="color: red;display: block;padding: 5px">{{errorList.brand}}</span>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">商品图片</label>
                            <div class="col-sm-6">
                                <input v-model="image" type="file" @change="fileUpload">
                                <!--                            <p class="help-block">Example block-level help text here.</p>-->
                            </div>
                            <span style="color: red;display: block;padding: 5px">{{uploadMsg}}</span>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">商品价格</label>
                            <div class="col-sm-6">
                                <input v-model="price" type="text" class="form-control" placeholder="请输入商品价格">
                            </div>
                            <span style="color: red;display: block;padding: 5px">{{errorList.price}}</span>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">商品数量</label>
                            <div class="col-sm-6">
                                <input v-model="num" type="text" class="form-control" placeholder="请输入商品数量">
                            </div>
                            <span style="color: red;display: block;padding: 5px">{{errorList.num}}</span>
                        </div>
                        <div v-if="isUpdate" class="form-group">
                            <label class="col-sm-2 control-label">商品状态</label>
                            <div class="col-sm-6">
                                <label class="radio-inline">
                                    <input v-model="status" type="radio" name="inlineRadioOptions" id="inlineRadio1"
                                           value="1"> 在售
                                </label>
                                <label class="radio-inline">
                                    <input v-model="status" type="radio" name="inlineRadioOptions" id="inlineRadio2"
                                           value="0"> 下架
                                </label>
                            </div>
                            <span style="color: red;display: block;padding: 5px">{{errorList.num}}</span>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">商品描述</label>
                            <div class="col-sm-6">
                                <textarea v-model="remark" class="form-control" rows="3" id="remark"
                                          placeholder="请输入部门描述" style="resize:none"></textarea>
                            </div>
                            <span style="color: red;display: block;padding: 5px">{{errorList.remark}}</span>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button v-if="isUpdate" type="button" class="btn btn-primary" @click="updateProduct(id)">修改</button>
                    <button v-else type="button" class="btn btn-primary" @click="addProduct">添加</button>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    //刷新表格
    function fresh() {
        setTimeout(() => {$('#table').bootstrapTable('refresh');},1)
    }
    //搜索
    //表格增删查改
    new Vue({
        el: '#app',
        data: {
            id: '',//商品id
            typeList: '',//类型列表
            type: '',//商品类型
            code: '',//商品编号
            productName: '',//商品名称
            brand: '',//商品品牌
            image: '',//商品图片
            price: '',//商品价格
            num: '',//商品数量
            status: '',//商品状态
            remark: '',//商品描述
            errorList: {},//错误信息
            isUpdate: false,//是否修改
            isUpload: false,//是否上传图片
            img: '',
            uploadMsg: '',//上传图片信息,
            session:''
        },
        created: function () {//页面初始化时加载
            this.getProductType()
        },
        methods: {
            //搜索
            search: function () {
                $('#table').bootstrapTable('refresh');
            },
            //获取商品类型
            getProductType: function () {
                axios.get('productType/queryAll').then((response) => {
                    this.typeList = response.data
                })
            },
            //新增商品
            addProduct: function () {
                var img = this.image.split("\\")
                axios.post('productInfo/insert', {
                    "pdCode": this.code,
                    "pdName": this.productName,
                    "tid": this.type.valueOf(),
                    "brand": this.brand,
                    "image": img[img.length - 1],
                    "price": this.price,
                    "num": this.num.valueOf(),
                    "remark": this.remark
                }).then((response) => {
                    if (response.data.code == '0') {
                        this.errorList = response.data.data
                    } else {
                        $("#table").bootstrapTable('refresh');
                        $('#myModal').modal('hide')
                        layer.msg('添加成功', {offset: '100px', icon: 1});
                    }
                })
            },
            //查找选择商品信息
            findProduct: function () {
                this.isUpdate = true
                var selectData = $("#table").bootstrapTable('getSelections')
                if (selectData != null && selectData.length > 0) {
                    $('#myModal').modal('show')
                    axios.get('productInfo/query/' + selectData[0].id).then((response) => {
                        var data = response.data.data
                        if (response.data.code == '1') {
                            this.id = data.id
                            this.code = data.pdCode
                            this.productName = data.pdName
                            this.type = data.tid
                            this.brand = data.brand
                            this.img = data.image
                            this.price = data.price
                            this.num = data.num
                            this.status = data.status
                            this.remark = data.remark
                        }
                    })
                } else {
                    layer.msg('当前无选择记录', {offset: '100px', icon: 2});
                }
            },
            //修改商品信息
            updateProduct: function (id) {
                var image
                if (this.isUpload) {
                    image = this.image.split("\\")
                    image = image[image.length - 1]
                } else {
                    image = this.img
                }
                axios.put('productInfo/update', {
                    "id": id,
                    "pdCode": this.code,
                    "pdName": this.productName,
                    "tid": this.type.valueOf(),
                    "brand": this.brand,
                    "image": image,
                    "price": this.price,
                    "num": this.num.valueOf(),
                    "status": this.status,
                    "remark": this.remark
                }).then((response) => {
                    if (response.data.code == '0') {
                        this.errorList = response.data.data
                    } else {
                        $("#table").bootstrapTable('refresh');
                        $('#myModal').modal('hide')
                        layer.msg('修改成功', {offset: '100px', icon: 1});
                        this.clearData()
                    }
                })
            },
            //清空data数据
            clearData: function () {
                this.id = ''
                // this.typeList=''
                this.type = ''
                this.code = ''
                this.productName = ''
                this.brand = ''
                this.image = ''
                this.price = ''
                this.num = ''
                this.remark = ''
                this.errorList = {}
                this.isUpdate = false
                this.isUpload = false
                this.img = ''
                this.uploadMsg=''
            },
            //商品图片上传
            fileUpload: function () {
                this.isUpload = true
                // var formData = new FormData() // 声明一个FormData对象
                var formData = new window.FormData() // vue 中使用 window.FormData(),否则会报 'FormData isn't definded'
                // 'userfile' 这个名字要和后台获取文件的名字一样;'userfile'是formData这个对象的键名
                formData.append('file', document.querySelector('input[type=file]').files[0])
                var options = {  // 设置axios的参数
                    url: 'upload',
                    data: formData,
                    method: 'post',
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
                axios(options).then((response) => {
                    if (response.data.code == '1') {
                        this.uploadMsg = '图片上传成功'
                    } else {
                        this.uploadMsg = '图片上传失败'
                    }
                }) // 发送请求
            }
        }
    })

    //设置table属性
    $('#table').bootstrapTable({
        url: 'productInfo/queryAll',
        method: "get",
        pagination: true, //启动分页
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        sortable: false,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 5,                       //每页的记录行数（*）
        pageList: [2, 5, 10, 20, 50, 'All'],        //可供选择的每页的行数（*）
        smartDisplay: false,                 //智能显示关每页的行数
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        strictSearch: false,
        showColumns: true,                  //是否显示所有的列
        showRefresh: true,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        height: 710,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
        uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,                   //是否显示父子表
        //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
        //设置为limit可以获取limit, offset, search, sort, order
        queryParamsType: "undefined",
        queryParams: function queryParams(params) {   //设置查询参数
            var param = {
                pageNumber: params.pageNumber,
                pageSize: params.pageSize,
                code: $.trim($('#s_code').val()),
                name: $.trim($('#s_productName').val()),
                brand: $.trim($('#s_brand').val()),
                type: $.trim($('#s_type').val()),
                low_p: $.trim($('#low_p').val()),
                high_p: $.trim($('#high_p').val())
                // offset: params.offset,  //页码
                // limit: params.limit,   //页面大小
                // orderNum : $("#orderNum").val()
            };
            return param;
        },
        onLoadSuccess: function () {  //加载成功时执行
            //复选框水平垂直居中显示
            $(".bs-checkbox").css({'text-align': 'center', 'vertical-align': 'middle'})
        },
        onLoadError: function () {  //加载失败时执行
            // layer.msg("加载数据失败", {time : 1500, icon : 2});
            // alert("加载数据失败")
        },
        //设置列属性
        columns: [{
            checkbox: true,
            visible: true,
        }, {
            title: '序号',
            width: 40,
            align: "center",
            valign: 'middle',
            formatter: function (value, row, index) {
                var pageSize = $('#table').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                var pageNumber = $('#table').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                return pageSize * (pageNumber - 1) + index + 1;    //返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
            }
        }, {
            field: 'id',
            title: 'id',
            align: "center",
            valign: 'middle',
        }, {
            field: 'pdCode',
            title: '商品编号',
            align: "center",
            valign: 'middle',
        }, {
            field: 'pdName',
            title: '商品名称',
            align: "center",
            valign: 'middle',
        }, {
            field: 'type',
            title: '商品类型',
            align: "center",
            valign: 'middle',
            formatter: function (value, row, index) {
                if (row.type) {
                    value = row.type.typeName
                }
                return value
            }
        }, {
            field: 'brand',
            title: '商品品牌',
            align: "center",
            valign: 'middle',
        }, {
            field: 'image',
            title: '商品图片',
            align: "center",
            valign: 'middle',
            formatter: function (value, row, index) {
                // var url = '<img width="100" height="80" src="' + 'upload/' + row.image + '">'
                var url = '<img width="100" height="80" src="' + '/image/' + row.image + '">'
                return url
            }
        }, {
            field: 'price',
            title: '商品价格',
            align: "center",
            valign: 'middle',
        }, {
            field: 'num',
            title: '商品数量',
            align: "center",
            valign: 'middle',
        }, {
            field: 'status',
            title: '状态',
            align: "center",
            valign: 'middle',
            formatter: function (value, row, index) {
                if (row.status == '1') {
                    value = '在售'
                } else {
                    value = '下架'
                }
                return value
            }
        }, {
            field: 'createTime',
            title: '创建时间',
            align: "center",
            valign: 'middle',
        }]
    })
    //获取选择的数据删除操作
    $("#btn_delete").click(function () {
        var selectData = $("#table").bootstrapTable('getSelections')
        if (selectData != null && selectData.length > 0) {
            var index = layer.confirm('是否删除改记录？', {
                offset: '100px',
                title: '删除提示',
                icon: 3,
                btn: ['取消', '删除',] //可以无限个按钮
            }, function () {
                layer.close(index)
            }, function () {
                axios.delete('productInfo/delete/' + selectData[0].id).then((response) => {
                    $("#table").bootstrapTable('refresh');
                    layer.msg('删除成功', {offset: '100px', icon: 1});
                })
                selectData = null
            });
        } else {
            layer.msg('当前无选择记录', {offset: '100px', icon: 2});
        }
    })
</script>
</html>